package main

import (
	"fmt"
	"math/rand"
	"strings"
	"time"

	"github.com/hkail/lolie/data"
)

type HeroBuilder struct {
	heroes []string
}

func NewHeroBuilder() (*HeroBuilder, error) {
	heroes, err := data.GetAllHeroesFromCSV()
	if err != nil {
		return nil, err
	}

	return &HeroBuilder{
		heroes: heroes,
	}, nil
}

func (b *HeroBuilder) RandomHeroes(count int) [][]string {
	heroes := make([][]string, 0, count)

	for i := 0; i < count; i++ {
		rand.Seed(time.Now().UnixNano())
		rand.Shuffle(len(b.heroes), func(i, j int) {
			b.heroes[i], b.heroes[j] = b.heroes[j], b.heroes[i]
		})

		heroes = append(heroes, append([]string{}, b.heroes[:15]...))
	}

	return heroes
}

func (b *HeroBuilder) Beatify(heroes []string) string {
	n := len(heroes) / 5
	beatifies := make([]string, 0, 5)

	for i := 0; i < 5; i++ {
		startIndex := i * n
		endIndex := startIndex + n
		beatifies = append(beatifies, fmt.Sprintf(NodeItemBeautifyTextMapper[i]+"-"+strings.Join(heroes[startIndex:endIndex], ",")))
	}

	return strings.Join(beatifies, "\n")
}

func (b *HeroBuilder) Remove(heroes []string) {
	heroSet := make(map[string]bool, len(heroes))
	for _, hero := range heroes {
		heroSet[hero] = true
	}

	newHeroes := make([]string, 0, len(b.heroes))
	for _, hero := range b.heroes {
		if heroSet[hero] {
			continue
		}

		newHeroes = append(newHeroes, hero)
	}

	b.heroes = newHeroes
}
